package com.example.practicespring.controller.userManage;


import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.practicespring.domain.SysRole;
import com.example.practicespring.domain.SysUserRole;
import com.example.practicespring.domain.User;
import com.example.practicespring.service.SysRoleService;
import com.example.practicespring.service.SysUserRoleService;
import com.example.practicespring.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@SaCheckRole("admin")
@RestController
@RequestMapping(value = "/userManage")
public class userManage {

    @Resource
    private UserService userService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysRoleService sysRoleService;

    @RequestMapping(value = "/userInfo", method = RequestMethod.POST)
    public SaResult userInfo() {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> users = userService.list(queryWrapper);

        QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
        List<SysUserRole> sysUserRoles = sysUserRoleService.list(sysUserRoleQueryWrapper);

        JSONObject roleMap = new JSONObject();
        QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
        List<SysRole> sysRoles = sysRoleService.list(sysRoleQueryWrapper);

        for(SysRole sysRole : sysRoles){
            roleMap.put(sysRole.getId().toString(), sysRole.getName());
        }

        // 增加角色名称
        for (User user : users) {
            for (SysUserRole sysUserRole : sysUserRoles)
                if (user.getId().equals(sysUserRole.getUserid()))
                    user.setRoleName(roleMap.getString(sysUserRole.getRoleid().toString()));
        }

        return SaResult.data(users).setMsg("用户数据获取成功！");
    }
}
